package cn.flying.cloud.base.common.excel;

import java.util.List;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;

import cn.flying.cloud.base.common.utils.Ft;


/**
 * 读Excel监听器
 *
 * @author: admin
 * @date: 2022年11月14日 19:29
 * @version: 1.0
 */
public class ExcelPageReadListener<T> implements ReadListener<T> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 每隔500条存储数据库，然后清理list ，方便内存回收
     */
    private final int batchCount;
    /**
     * 缓存队列
     */
    private List<T> cachedDataList;
    /**
     * Excel数据处理对象
     */
    private final Consumer<List<T>> consumer;

    /**
     * @param consumer
     */
    public ExcelPageReadListener(Consumer<List<T>> consumer) {
        this.consumer = consumer;
        this.batchCount = 500;
        this.cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
    }

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param consumer
     */
    public ExcelPageReadListener(Consumer<List<T>> consumer, int batchCount) {
        this.consumer = consumer;
        this.batchCount = batchCount == 0 ? 500 : batchCount;
        this.cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        if (logger.isDebugEnabled()) {
            logger.debug("解析到一条数据:{}", Ft.JSON.serializer(data));
        }
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= this.batchCount) {
            this.consumer.accept(this.cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(this.batchCount);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        this.consumer.accept(this.cachedDataList);
        logger.info("所有数据解析完成！");
    }
}
